<?php
/*
 * @Author: CHINAKAIYUAN<sunkaiyuan@namenode.cn>
 * @Date: 2022-02-02 19:42:06
 * @LastEditTime: 2023-01-04 15:41:25
 * @LastEditors: sunkaiyuan sunkaiyuan@namenode.com
 * @Description: 
 */

namespace App\Repositories;

use App\Models\Dic;
use App\Models\DicCategory;
use Illuminate\Http\Request;

class DicRepository extends Repositories
{


    public $category;
    public function __construct(Dic $model, DicCategory $category)
    {
        $this->model = $model;
        $this->category = $category;
    }

    public function category()
    {
        return $this->category;
    }
    public function getCategory()
    {
        return $this->category->with(["children"])->where('parent_id', 0)->get();
    }

    public function getDicData($code)
    {
        $data = $this->category->whereStatus(1)->whereCode($code)->get();

        return $data;
    }
    public function search($request = null)
    {

        if ($request->has("dic_category_id")) {
            $this->whereDicCategoryId($request->input("dic_category_id"));
        }
        return parent::search($request);
    }


    public function saveCategory($data)
    {
        $data = array_filter($data);
        $id = isset($data['id']) ? $data['id'] : 0;

        $data = $this->category->updateOrCreate(['id' => $id], $data);

        return $data->id;
    }

    public function enable($id)
    {
        $mode_data = $this->whereId($id)->first();
        $mode_data->status = $mode_data->status == "1" ? "0" : "1";

        return $mode_data->save();
    }
    public function delete($ids)
    {
        return $this->whereIn("id", $ids)->get()->filter(function ($v) {
            return $v->delete();
        });
    }
    public function deleteCategory($id)
    {
        //递归删除整个树形菜单
        return treeListCallBack(
            $this->category
                ->with(['children', 'dic'])
                ->whereId($id)
                ->get(),
            //拉出要删除的数据
            function ($model) {
                //删除数据组对应的明细
                !$model->dic->isEmpty() && $model->dic->filter(
                    function ($v) {
                        $v->delete();
                    }
                );
                //删除组
                $model->delete();
                return $model;
            }
        );
    }
}